package com.huffman.smart_picture.aop.aspect;

import com.huffman.smart_picture.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author DengLin
 * @title 日志记录
 * @date 2024/07/03
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    @Around("execution(public * com.huffman.smart_picture.controller.*.*(..))")
    public Object logRequestRecord(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String url = request.getRequestURI();
        String ip = request.getRemoteHost();
        Object[] args = joinPoint.getArgs();
        String requestId = UUID.randomUUID().toString();
        String params = StringUtil.join(args, ",");
        log.info("request start, id:{}, ip:{}, url:{}, params:{}", requestId, ip, url, params);
        Object result = joinPoint.proceed();
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        log.info("request end, id:{}, cost:{}, result:{}", requestId, totalTimeMillis,result);
        return result;
    }
}
